package leetcode.L500;

import java.util.Stack;

public class EX227 {
    public int calculate(String s) {
        Stack<Integer> nums = new Stack<>();
        Stack<Integer> sign = new Stack<>();
        int res = 0;


            sign.push(1);


        for (int i = 0; i < s.length(); i++) {
            if(isDigit(s.charAt(i))){
                res = s.charAt(i)-'0';
                while (i+1<s.length()&&isDigit(s.charAt(i+1))){
                    res = res*10+s.charAt(++i)-'0';
                }
            }
            else if(s.charAt(i)=='+'){
                nums.push(res);
                res = 0;
                sign.push(1);
            }
            else if(s.charAt(i)=='-'){
                nums.push(res);
                res = 0;
                sign.push(-1);
            }
            else if(s.charAt(i)=='*'){
                while (s.charAt(i+1)==' '){
                    i++;
                }
                int temp = s.charAt(++i)-'0';
                while (i+1<s.length()&&isDigit(s.charAt(i+1))){
                    temp = temp*10+s.charAt(++i)-'0';
                }
                res = res*temp;
            }
            else if(s.charAt(i)=='/'){
                while (s.charAt(i+1)==' '){
                    i++;
                }
                int temp = s.charAt(++i)-'0';
                while (i+1<s.length()&&isDigit(s.charAt(i+1))){
                    temp = temp*10+s.charAt(++i)-'0';
                }
                res = res/temp;
            }
        }
        nums.push(res);
        res = 0;
        while (!sign.isEmpty()){
            res=res+nums.pop()*sign.pop();
        }
        return res;
    }
    public boolean isDigit(char a){
        if(a=='+'||a=='-'||a=='*'||a=='/'||a==' '){
            return false;
        }else {
            return true;
        }
    }

    public static void main(String[] args) {
        EX227 ex227 = new EX227();
        int calculate = ex227.calculate(" 3+5 / 2 ");
        System.out.println(calculate);
    }
}
